package com.atguigu.gmall.publisher.controller;

import com.atguigu.gmall.publisher.beans.KeywordStats;
import com.atguigu.gmall.publisher.beans.ProductStats;
import com.atguigu.gmall.publisher.beans.ProvinceStats;
import com.atguigu.gmall.publisher.beans.VisitorStats;
import com.atguigu.gmall.publisher.service.KeywordStatsService;
import com.atguigu.gmall.publisher.service.ProductStatsService;
import com.atguigu.gmall.publisher.service.ProvinceStatsService;
import com.atguigu.gmall.publisher.service.VisitorStatsService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * Author: Felix
 * Date: 2021/8/16
 * Desc: 大屏展示的控制层
 */
@RestController
@RequestMapping("/api/sugar")
public class SugarController {
    @Autowired
    //商品统计service层
    private ProductStatsService productStatsService;

    @Autowired
    //地区统计service层
    private ProvinceStatsService provinceStatsService;

    @Autowired
    //访客统计Service层
    private VisitorStatsService visitorStatsService;

    @Autowired
    //关键词统计Service层
    private KeywordStatsService keywordStatsService;

    //获取某天的总成交易额
    @RequestMapping("/gmv")
    public String getGMV(@RequestParam(value = "date",defaultValue = "0") Integer date){
        //获取当前日期
        if (date == 0) {
            date = now();
        }

        //调用service获取总交易额
        BigDecimal gmv = productStatsService.getGMV(date);

        //拼接json
        String json = "{\"status\": 0,\"data\":" + gmv + "}";
        return json;
    }

    //获取品牌对应的成交额
    //面向数组方式
    @RequestMapping("/tm")
    public String getProductStatsByTm(
            @RequestParam(value = "date",defaultValue = "0")Integer date,
            @RequestParam(value = "limit",defaultValue = "20")Integer limit){
        //获取当前日期
        if (date == 0){
            date = now();
        }

        //调用service方法，获取品牌交易额
        List<ProductStats> productStatsList = productStatsService.getProductStatsByTm(date, limit);

        //对查询结果进行遍历，获取品牌以及品牌交易额；将品牌以及品牌交易额分别封装到独立的ArrayList集合中的List
        List<String> tmList = new ArrayList<>();
        List<BigDecimal> amountList = new ArrayList<>();
        for (ProductStats productStats : productStatsList){
            tmList.add(productStats.getTm_name());
            amountList.add(productStats.getOrder_amount());
        }

        //拼接json
        String json = "{\"status\":0,\"data\":" +
                "{\"categories\":[\"" + StringUtils.join(tmList,"\",\"") + "\"]," +
                "\"series\":[{\"name\":\"商品品牌\",\"data\":["+ StringUtils.join(amountList,",") +"]}]}}";
        return json;
    }

//    //面向字符方式
//    @RequestMapping("/category3")
//    public String getProductStatsByCategory3(
//        @RequestParam(value = "date", defaultValue = "0") Integer date,
//        @RequestParam(value = "limit", defaultValue = "20") Integer limit) {
//        if (date == 0) {
//            date = now();
//        }
//
//        //调用service方法，获取品类销售排名情况
//        List<ProductStats> productStatsList = productStatsService.getProductStatsByCategory3(date, limit);
//
//        //拼接json
//        StringBuilder jsonBuilder = new StringBuilder("{\"status\": 0,\"data\": [");
//
//        //遍历集合，获取每一个品类的销售情况
//        for (int i = 0; i < productStatsList.size(); i++) {
//            ProductStats productStats = productStatsList.get(i);
//            jsonBuilder.append("{\"name\": \"" + productStats.getCategory3_name() + "\"" +
//                ",\"value\": "+productStats.getOrder_amount()+"}");
//            if(i < productStatsList.size() -1 ){
//                jsonBuilder.append(",");
//            }
//        }
//
//        jsonBuilder.append("]}");
//        return jsonBuilder.toString();
//    }

    //获取品类对应的成交额
    @RequestMapping("/category3")
    public Object getProductStatsByCategory3(
            @RequestParam(value = "date",defaultValue = "0")Integer date,
            @RequestParam(value = "limit",defaultValue = "20")Integer limit){
        //获取当前日期
        if (date == 0) {
            date = now();
        }
        //调用service方法，获取品类销售排名情况
        List<ProductStats> productStatsList = productStatsService.getProductStatsByCategory3(date, limit);

        //对查询结果进行遍历,将品类名称以及下单商品金额封装到独立的HashMap的Map中,拼接json
        //把传递的参数放到独立的HashMap的Map中,最后放到ArrayList
        Map resMap = new HashMap();
        List dataList = new ArrayList();
        for (ProductStats productStats : productStatsList){
            Map dataMap = new HashMap();
            dataMap.put("name",productStats.getCategory3_name());
            dataMap.put("value",productStats.getOrder_amount());
            dataList.add(dataMap);
        }
        resMap.put("status",0);
        resMap.put("data",dataList);
        return resMap;
    }

    //获取SPU对应的成交额
    @RequestMapping("/spu")
    public String getProductStatsBySPU(
            @RequestParam(value = "date",defaultValue = "0") Integer date,
            @RequestParam(value = "limit",defaultValue = "20")Integer limit){
        //获取当前日期
        if (date == 0) {
            date = now();
        }

        //从service中获取SPU对应的成交额
        List<ProductStats> productStatsList = productStatsService.getProductStatsBySPU(date, limit);

        //对查询结果进行遍历,将spu名称以及下单商品金额,订单数封装到独立的StringBuilder中，拼接json
        StringBuilder jsonB = new StringBuilder(
                "{\"status\":0,\"data\":{\"columns\":[{\"name\":\"商品名称\",\"id\":\"name\"}," +
                "{\"name\":\"交易额\",\"id\":\"amount\"},{\"name\":\"订单数\",\"id\":\"ct\"}],\"rows\":[");
        for (int i = 0;i < productStatsList.size();i++){
            ProductStats productStats = productStatsList.get(i);
            jsonB.append(
                    "{\"name\":\"" + productStats.getSpu_name() + "\"," +
                    "\"amount\": " + productStats.getOrder_amount() + "," +
                    "\"ct\": " + productStats.getOrder_ct() + "}");
            if (i < productStatsList.size() - 1){
                jsonB.append(",");
            }
        }
        jsonB.append("]}}");
        return jsonB.toString();
    }

    //不同地区交易金额
    @RequestMapping("/province")
    public String getProvinceStats(@RequestParam(value = "date",defaultValue = "0")Integer date){
        //获取当前日期
        if (date == 0){
            date = now();
        }
        //从service中获取地区交易金额
        List<ProvinceStats> provinceStatsList = provinceStatsService.getProvinceStats(date);

        //对查询结果进行遍历,将省份名称以及订单金额封装到独立的StringBuilder中，拼接json
        StringBuilder json = new StringBuilder("{\"status\":0,\"data\":{\"mapData\":[");
        for (int i = 0; i < provinceStatsList.size();i++){
            ProvinceStats provinceStats = provinceStatsList.get(i);
            if (i >= 1){
                json.append(",");
            }
            json.append("{\"name\":\"" + provinceStats.getProvince_name() + "\"," +
                    "\"value\":" + provinceStats.getOrder_amount() + "}");
        }
        json.append("],\"valueName\":\"交易额\"}}");
        return json.toString();
    }
    //新老用户对比
    @RequestMapping("/visitor")
    public String getVisitorStats(@RequestParam(value = "date",defaultValue = "0")Integer date){
        //获取当前日期
        if (date == 0){
            date = now();
        }

        //调用service获取新老用户
        List<VisitorStats> visitorStatsList = visitorStatsService.getVisitorStats(date);
        //声明新访客
        VisitorStats newVisitorStats = new VisitorStats();
        //声明老访客
        VisitorStats oldvisitorStats = new VisitorStats();
        //确定新老用户
        for (VisitorStats visitorStats : visitorStatsList){
            //if(visitorStats.getIs_new().equals("1")){
            if ("1".equals(visitorStats.getIs_new())){
                //新访客
                newVisitorStats = visitorStats;
            }else {
                //老访客
                oldvisitorStats = visitorStats;
            }
        }

        //拼接json
        String json = "{\"status\":0,\"data\":" +
                "{\"columns\":[" +
                "{\"name\":\"类别\",\"id\":\"type\"}," +
                "{\"name\":\"新用户\",\"id\":\"new\"}," +
                "{\"name\":\"老用户\",\"id\":\"old\"}]," +
                "\"rows\":[" +
                "{\"type\":\"用户数(人)\",\"new\":" + newVisitorStats.getUv_ct() + ",\"old\":" +
                oldvisitorStats.getUv_ct() + "}," +
                "{\"type\":\"总访问页面(次)\",\"new\":" + newVisitorStats.getPv_ct() + ",\"old\":" +
                oldvisitorStats.getPv_ct() + "}," +
                "{\"type\":\"跳出率(%)\",\"new\":" + newVisitorStats.getUjRate() + ",\"old\":" +
                oldvisitorStats.getUjRate() +"}," +
                "{\"type\":\"平均在线时长(秒)\",\"new\":" + newVisitorStats.getDurPerSv() + ",\"old\":" +
                oldvisitorStats.getDurPerSv() + "}," +
                "{\"type\":\"平均访问页面数(次)\",\"new\":" + newVisitorStats.getPvPerSv() + ",\"old\":" +
                oldvisitorStats.getPvPerSv() + "}]}}";
        return json;
    }

    //用户访问分时
    @RequestMapping("/hr")
    public String getVisitorStatsByHr(@RequestParam(value = "date",defaultValue = "0") Integer date){
        //获取当前日期
        if(date == 0){
            date = now();
        }

        //从service中获取分时访问情况
        List<VisitorStats> visitorStatsList = visitorStatsService.getVisitorStatsByHr(date);
        //定义一个数组(类) ，用于存放24小时的分时统计情况
        VisitorStats[] visitorStatsArr = new VisitorStats[24];
        //从集合中获取结果，赋值给数组中对应的小时
        for ( VisitorStats visitorStats : visitorStatsList){
            visitorStatsArr[visitorStats.getHr()] = visitorStats;
        }

        //用于存放24小时的集合
        List hrList = new ArrayList();
        //用于存放每个小时uv情况的集合
        List uvList = new ArrayList();
        //用于存放每个小时pv情况的集合
        List pvList = new ArrayList();
        //用于存放新访客每个小时uv情况的集合
        List newUvList = new ArrayList();

        //从数组中获取一天24小时的数据
        for (int hr = 0; hr < visitorStatsArr.length; hr++){
            VisitorStats visitorStats = visitorStatsArr[hr];
            //加入独立访客数,页面访问数,新用户数
            if (visitorStats != null){
                uvList.add(visitorStats.getUv_ct());
                pvList.add(visitorStats.getPv_ct());
                newUvList.add(visitorStats.getNew_uv());
            }else {
                uvList.add(0L);
                pvList.add(0L);
                newUvList.add(0L);
            }
            //%02d（两位数字,不够补零）
            hrList.add(String.format("%02d",hr));
        }

        //拼接json
        String json = "{\"status\":0,\"data\":{\"categories\":" +
                "[\"" + StringUtils.join(hrList,"\",\"") + "\"]," +
                "\"series\":[" +
                "{\"name\":\"UV\",\"data\":[" + StringUtils.join(uvList,",") + "]}," +
                "{\"name\":\"PV\",\"data\":[" + StringUtils.join(pvList,",") + "]}," +
                "{\"name\":\"newUV\",\"data\":[" + StringUtils.join(newUvList,",") + "]}" +
                "]}}";
        return json;
    }

    //热度关键词占比
    @RequestMapping("/keyword")
    public String getKeywordStats(
            @RequestParam(value = "date",defaultValue = "0")Integer date,
            @RequestParam(value = "limit",defaultValue = "20")Integer limit){
        //获取当前日期
        if (date == 0){
            date = now();
        }
        //从service中获取热度关键词
        List<KeywordStats> keywordStatsList = keywordStatsService.getkeywordStats(date, limit);

        //对查询结果进行遍历,将ik分词以及ik分词数封装到独立的StringBuilder中，拼接json
        StringBuilder json = new StringBuilder("{\"status\":0,\"data\":[");
        for (int i = 0; i < keywordStatsList.size(); i++) {
            KeywordStats keywordStats = keywordStatsList.get(i);
            json.append("{\"name\":\"" + keywordStats.getKeyword() + "\",\"value\":" + keywordStats.getCt() + "}");
            if (i < keywordStatsList.size() -1){
                json.append(",");
            }

        }
        json.append("]}");
        //返回json并转为String
        return json.toString();
    }

    //获取当前日期
    private Integer now() {
        String yyyyMMdd = DateFormatUtils.format(new Date(), "yyyyMMdd");
        return Integer.valueOf(yyyyMMdd);
    }
}
